import asyncio
import re

from loguru import logger

from com.arcfox.middleware import async_mysql_middleware as db
from com.arcfox.util.muilty_coroutine_util import concurrency

page_size = 5000


@concurrency(10)
async def update_data(**params):
    data = params['task']
    sql = f"update tb_enrollment_plan set major_name = '{data['major_name']}' where id = {data['record_id']} limit 1"
    try:
        await db.save_or_update(sql)
    except:
        pass


async def get_data(start):
    data_list = []
    sql = f"select id, plan_major_name from tb_enrollment_plan where major_name is null limit 0, {page_size}"
    resp = await db.query_all(sql)
    for item in resp:
        record_id = item[0]
        plan_major_name = item[1]
        major_name = process_major_name(plan_major_name)
        data_list.append({"record_id": record_id, "plan_major_name": plan_major_name, "major_name": major_name})
    return data_list


def process_major_name(plan_major_name):
    if plan_major_name:
        results = re.split(r'[(（]', plan_major_name)
        major_name = results[0]
        #logger.info(f"before: {plan_major_name} after: {major_name}")
        return major_name
    return None


async def start():
    page = 0
    while True:
        start_index = page * page_size
        logger.info(f"开始处理第{page + 1}页数据")
        data_list = await get_data(start_index)
        if not data_list:
            logger.info(f"数据已处理完成, 共{page + 1}页")
            return
        await update_data(tasks=data_list)
        page += 1


if __name__ == "__main__":
    asyncio.run(start())
